package com.tdx.blog_nowcoder.controller;

import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.tdx.blog_nowcoder.annotation.LoginRequired;
import com.tdx.blog_nowcoder.constant.CommentReplyConstant;
import com.tdx.blog_nowcoder.entity.User;
import com.tdx.blog_nowcoder.service.FollowService;
import com.tdx.blog_nowcoder.service.LikeService;
import com.tdx.blog_nowcoder.service.UserService;
import com.tdx.blog_nowcoder.utils.DumpJSONToString;
import com.tdx.blog_nowcoder.utils.RandomUUID;
import com.tdx.blog_nowcoder.utils.ThreadHostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

import static com.tdx.blog_nowcoder.constant.CommentReplyConstant.ENTITY_TYPE_USER;

@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;
    @Autowired
    private ThreadHostHolder threadhostHolder;

    @Autowired
    private FollowService followService;

    @Value("${project.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String  contextPath;

    @Value("${project.path.imageUpload}")
    private String uploadPath;

    @Value("${qiniu.access.key}")
    private String qiu_ak;

    @Value("${qiniu.secret.key}")
    private String qiu_sk;

    @Value("${qiniu.bucket.header.name}")
    private String qiu_headerNamespace;

    @Value("${quniu.bucket.header.url}")
    private String qiu_headerUrl;


    @RequestMapping(path = "/setting")
    @LoginRequired
    public String settingPage(Model model){
        //获取文件名
        String fileName = RandomUUID.getUUID();
        //设置响应状态
        StringMap policy = new StringMap();
        policy.put("returnBody", DumpJSONToString.getJsonString(200,"success"));
        //发送认证
        Auth auth = Auth.create(qiu_ak,qiu_sk);
        String uploadToken = auth.uploadToken(qiu_headerNamespace,fileName,3600,policy);
        model.addAttribute("uploadToken", uploadToken);
        model.addAttribute("fileName", fileName);
        return "site/setting";
    }

    // 更新头像路径
    @RequestMapping(path = "/header/url", method = RequestMethod.POST)
    @ResponseBody
    public String updateHeaderUrl(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return DumpJSONToString.getJsonString(404, "文件名不能为空!");
        }

        String url = qiu_headerUrl + "/" + fileName;
        userService.updateHeader(threadhostHolder.getUser().getId(), url);

        System.out.println(url);
        return DumpJSONToString.getJsonString(200);
    }




    @RequestMapping(path = "/imgUpload",method = RequestMethod.POST)
    @LoginRequired
    public String uploadImage(MultipartFile imgFile, Model model){

        System.out.println(imgFile);
        if(imgFile==null){
            model.addAttribute("error"," 您还没有选择图片!");
            return "site/setting";
        }
        String originalfileName = imgFile.getOriginalFilename();
        String suffix = originalfileName.substring(originalfileName.lastIndexOf('.'));

        if (StringUtils.isBlank(suffix)||!(suffix.equals("png")||suffix.equals(".jpg")||suffix.equals(".jpeg"))) {
            model.addAttribute("error", "文件的格式不正确!");
            return "site/setting";
        }

        //存文件到本地i
        String fileName = RandomUUID.getUUID() +suffix;
        File filedest = new File(uploadPath+"/"+fileName);
        try {
            imgFile.transferTo(filedest);
        } catch (IOException e) {
            logger.error("上传文件失败: " + e.getMessage());
            throw new RuntimeException("上传文件失败,服务器发生异常!", e);
        }
        // 更新当前用户的头像的路径(web访问路径)
        // http://localhost:8080/community/user/header/xxx.png
        User user = threadhostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + fileName;
        userService.updateHeader(user.getId(), headerUrl);

        return "redirect:/index";


    }

    @RequestMapping(path = "/header/{fileName}",method = RequestMethod.GET)
    public void getImageHeader(@PathVariable("fileName") String filename, HttpServletResponse response){
        if(StringUtils.isBlank(filename)){
            logger.error("文件名无效: ");
            return;
        }
        String file_name = uploadPath +"/"+filename;
        // 文件后缀
        String suffix = file_name.substring(file_name.lastIndexOf("."));

        if (StringUtils.isBlank(suffix)||!(suffix.equals("png")||suffix.equals(".jpg")||suffix.equals(".jpeg"))) {
            logger.error("文件格式有误！");
            return;
        }
        // 响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(file_name);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败: " + e.getMessage());
        }
    }


    @RequestMapping(path = "/profile/{userId}",method = RequestMethod.GET)
    public String getUserProfilePage(@PathVariable("userId") int userId, Model model){
        User user = userService.selectUserById(userId);
        if(user==null){
            throw new RuntimeException("该用户不存在!");
        }

        // 用户
        model.addAttribute("user", user);

        // 点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        //关注的实体数量
        long followeeCount = followService.getFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);

        // 粉丝数量

        long followerCount = followService.getFollowerCount(ENTITY_TYPE_USER,userId);
        model.addAttribute("followerCount",followerCount);

        //是否已经关注
        boolean hasFollowed = false;
        if(threadhostHolder.getUser()!=null){
            hasFollowed = followService.hasFollowed(threadhostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }
        model.addAttribute("hasFollowed",hasFollowed);

        return "/site/profile";
    }

}
